import config from "../config/index";
const tabPageList = [
]

class wxFun {

    /**
   * page -> config 声明的页面名称 或者完整路径，都可以
   * params 页面的参数 => Object -> pageType:跳转类型(navigateTo,redirectTo,reLaunch,switchTab)   其他key是正常参数
   * dataset 点击事件  -> params  页面的参数(同上面、对象字符串)
   * */
    toPage({ page = '', params = {}, dataset = null }) {
        if (dataset) {
            let $data = this.getDataSet(dataset);
            console.log($data)
            if ($data.hasOwnProperty('page')) {
                page = $data.page;
                /** 判断是否有传参*/
                if ($data.hasOwnProperty('params')) {
                    if (wx.$util.isJson($data[params])) {
                        params = { ...JSON.parse($data['params']) }
                    } else {
                        params = $data['params'];
                    }
                }
            }
        }
        console.log('dataset====', dataset)
        let url = page.indexOf('/') > -1 ? page : this.getPagePath(page);
        if (!url) {
            return false;
        }
        let pageType = 'navigateTo';
        if (params) {
            let str = '';
            for (let i in params) {
                if (i === 'pageType') {
                    pageType = params[i];
                } else {
                    str += `&${i}=${params[i]}`;
                }
            }
            if (str) {
                url += '?' + str.substr(1);
            }
        }

        // 判断路径是否属于 tab 路径
        if (tabPageList.includes(url)) {
            pageType = 'switchTab'
        }
        wx[pageType]({
            url
        });
    }

    /** 获取dataset
  *  $isDetail 是否也需要返回detail
  * */
    getDataSet(ev, $isDetail = false) {
        if (!ev) return {};
        if ($isDetail) {
            return {
                dataset: ev.currentTarget.dataset,
                detail: ev.detail,
            }
        }
        return ev.currentTarget.dataset;
    }

    getPagePath(key) {
        const obj = config.page[key] || {}
        return obj.path || ''
    }

    // 消息提示框
    showToast(title = '即将开放', icon = 'none', duration = 2000, success, fail, complete) {
        wx.showToast({
            icon,
            duration,
            title,
            success: (ev) => {
                if (success) success(ev)
            },
            fail: (ev) => {
                if (fail) fail(ev)
            },
            complete: (ev) => {
                if (complete) complete(ev)
            },
        });
    }

    //显示 loading 提示框
    showLoading(title = '加载中...') {
        wx.showLoading({
            title: title,
            mask: true
        })
    }

    //hide loading 提示框
    hideLoading() {
        wx.hideLoading();
        wx.stopPullDownRefresh();
    }

    logout(cb) {
        getApp().globalData.isLogin = false
        wx.removeStorageSync('token')
        wx.reLaunch({
            url: '/pages/login/index',
        })
        typeof cb === 'function' && cb()
    }

    // 获取 token
    async getToken(cb) {
        const app = getApp()
        let openId = ''
        try {
            openId = wx.getStorageSync('openId')
        } catch {
        }
        if (!openId) return
        try {
            const tokenRes = await wx.$Api.auth.getToken({
                data: {
                    client_id: 'member',
                    client_secret: 'secret',
                    grant_type: 'mini_auth',
                    OpenId: openId
                }
            })

            wx.setStorage({
                key: 'token',
                data: `${tokenRes.token_type} ${tokenRes.access_token}`,
                success() {
                    app.globalData.isLogin = true
                    typeof cb === 'function' && cb()
                }
            })
        } catch (e) {
            wx.$Fun.showToast('登录失败，请联系管理员')
        }
    }

    // 微信登录
    wxLogin() {
        return new Promise((resolve, reject) => {
            wx.login({
                success(res) {
                    resolve(res)
                },
                fail() {
                    reject({
                        wxLoginFail: true
                    })
                }
            })
        })
    }

    // 微信支付
    async wxPay(options) {
        return new Promise((resolve, reject) => {
            wx.requestPayment({
                timeStamp: options.timeStamp || options.TimeStamp,
                nonceStr: options.nonceStr || options.NonceStr,
                package: options.package || options.Package,
                signType: options.signType || options.SignType,
                paySign: options.paySign || options.PaySign,
                success(res) {
                    resolve(res)
                },
                fail(err) {
                    reject(err)
                }
            })
        })
    }
}

let $wxFun = new wxFun;
module.exports = $wxFun;
wx.$Fun = $wxFun;
